<script lang="ts" setup>
  import { postFetch } from '@/api/common'
  import { DictItem } from '@/types/dict'
  import { flatListToTree } from '@/utils/flatListToTree'
  const defaultProps = {
    label: 'name',
    children: 'children',
  }
  interface Props {
    modelValue?: string
    dicCode?: string
  }
  const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    dicCode: '',
    data: () => [],
  })
  const dataList = ref<DictItem[]>([])
  // 判断是否有子节点
  const hasChildren = (node: any) => {
    return node.some((item) => 'children' in item)
  }
  const getData = async () => {
    const res = await postFetch('/dict/getDicDataCode', {
      dictCode: props.dicCode,
    })
    dataList.value = hasChildren(res) ? res : flatListToTree(res)
  }
  const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void
    (e: 'update:modelStatus', value: number): void
  }>()

  const handleNodeClick = (data: DictItem) => {
    console.log('当前选中节点:', data)
    emit('update:modelValue', data.name)
    emit('update:modelStatus', data.value)
  }
  // const handleClear = () => {
  //   emit('update:modelValue', '')
  // }
  watch(
    () => props.dicCode,
    () => {
      getData()
    },
  )
  onMounted(() => {
    if (props.dicCode) {
      getData()
    }
  })
</script>

<template>
  <el-tree-select
    :model-value="props.modelValue"
    :data="dataList"
    :props="defaultProps"
    check-strictly
    clearable
    node-key="id"
    :render-after-expand="false"
    @node-click="handleNodeClick"
    @clear="emit('update:modelValue', null)"
  />
</template>
